package com.trafficsys.modules.loginAndRegister.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author Zhao Bin
 * @Date 2021/9/28 16:58
 * @Version 1.0
 *
 * 限制同一ip地址访问频率
 */
@Component
public class Limit {
    @Autowired
    private StringRedisTemplate redisTemplate;
    //单位时间  1分钟
    private static final int UNIT_TIME = 1;
    //同一ip单位时间最大访问次数 1分钟访问30次
    private static final int MAX_VISIT_COUNT = 30;
    // redis 记录用户已访问次数
    private static final String NOW_COUNT ="NOW:VISIT:COUNT:";
    /**
     * 根据key获取计数器
     */
    private RedisAtomicInteger getRedisCounter(String key){
        RedisAtomicInteger counter=
                new RedisAtomicInteger(key,redisTemplate.getConnectionFactory());
        if(counter.get() == MAX_VISIT_COUNT){
            counter.expire(UNIT_TIME, TimeUnit.MINUTES);
        }
        return counter;
    }
    public HashMap<String,Object> limit(HttpServletRequest request){
        //如果没有达到最大限制频率 就返回true 达到限制返回false
        String key=NOW_COUNT+request.getRemoteAddr();//redis的key NOW:VISIT:COUNT:IP号
        HashMap<String,Object> map=new HashMap<>();
        RedisAtomicInteger counter=getRedisCounter(key);
        if(counter.get() >=MAX_VISIT_COUNT){
            map.put("state","NoPass");
            return map;
        }else{
            counter.getAndIncrement();
            map.put("state","Pass");
        }
        return map;
    }
}
